//
//  SXTRegisterNextView.m
//  SYT
//
//  Created by 彭之耀 on 2017/9/10.
//  Copyright © 2017年 个人学习. All rights reserved.
//

#import "SXTRegisterNextView.h"

@interface SXTRegisterNextView()<UITextFieldDelegate>

/**
 提示验证码发送到XXX手机
 */
@property (strong,nonatomic) UILabel *tostLabel;
/**
 背景，边框
 */
@property (strong,nonatomic) UILabel *backLabel;
/**
 验证码输入框
 */
@property (strong,nonatomic) UITextField *codeText;
/**
 倒计时button，当倒计时结束后变成发送验证码
 */
@property (strong,nonatomic) UIButton *timeButton;
/**
 输入框与倒计时button之间的竖线
 */
@property (strong,nonatomic) UILabel *lineLabel;
/**
 注册按钮
 */
@property (strong,nonatomic) UIButton *registerButton;

@end

@implementation SXTRegisterNextView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

-(instancetype)init{
    if(self){
        self = [super init];
//        self.backgroundColor = [UIColor redColor];
        [self addSubview:self.tostLabel];
        [self addSubview:self.backLabel];
        [self addSubview:self.codeText];
        [self addSubview:self.timeButton];
        [self addSubview:self.lineLabel];
        [self addSubview:self.registerButton];
        [self GCDTime:60];
    }
    return self;
}

-(void)layoutSubviews{
    __weak typeof (self) weakSelf = self;
    [_tostLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@35);
        make.top.right.equalTo(weakSelf);
        make.left.equalTo(weakSelf.mas_left).offset(15);
    }];
    [_backLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.tostLabel.mas_bottom).offset(-1);
        make.height.mas_equalTo(@46);
        make.centerX.equalTo(weakSelf.mas_centerX);
        make.width.mas_equalTo(VIEW_WIDTH+2);
    }];
    [_codeText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf).offset(15);
        make.right.equalTo(weakSelf.lineLabel.mas_left).offset(-4);
        make.height.equalTo(@44);
        make.top.equalTo(weakSelf.tostLabel.mas_bottom);
    }];
    [_timeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(100, 44));
        make.right.top.equalTo(weakSelf.backLabel);
    }];
    [_lineLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(1, 30));
        make.centerY.equalTo(weakSelf.backLabel.mas_centerY);
        make.right.equalTo(weakSelf.timeButton.mas_left).offset(-1);
    }];
    [_registerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.mas_left).offset(16);
        make.right.equalTo(weakSelf.mas_right).offset(-16);
        make.height.equalTo(@35);
        make.top.equalTo(weakSelf.backLabel.mas_bottom).offset(15);
    }];
}

-(void)codeTextChange:(UITextField *)codeText{
    if (codeText.text.length == 6) {
        _registerButton.userInteractionEnabled = YES;
        _registerButton.backgroundColor = rgb(56, 166, 241);
    }else{
        _registerButton.userInteractionEnabled = NO;
        _registerButton.backgroundColor = rgb(229, 229, 229);
    }
    
}

-(NSMutableAttributedString *)makeTimeButtonAttributeText:(NSInteger)time{
    NSMutableAttributedString *string3 = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%li",time] attributes:@{NSForegroundColorAttributeName:rgb(56, 166, 243)}];
    NSMutableAttributedString *string4 = [[NSMutableAttributedString alloc]initWithString:@"秒后重试" attributes:@{NSForegroundColorAttributeName:rgb(139, 139, 139)}];
    [string3 insertAttributedString:string4 atIndex:string3.length];
    return string3;
}

-(NSMutableAttributedString *)makeTostLabelAttributeText{
    NSMutableAttributedString *string1 = [[NSMutableAttributedString alloc]initWithString:@"验证码已经发送到" attributes:@{NSForegroundColorAttributeName:rgb(139, 139, 139)}];
    NSMutableAttributedString *string2 = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@" +86 %@",_phoneNumString] attributes:@{NSForegroundColorAttributeName:rgb(56, 166, 243)}];
    [string1 insertAttributedString:string2 atIndex:string1.length];
    return string1;
}

-(void)onClickTimeButton{
    NSLog(@"重新发送验证码");
    _timeButton.userInteractionEnabled = NO;
    [self GCDTime:60];
}

#pragma mark - 懒加载、初始化

-(UILabel *)tostLabel{
    if(!_tostLabel){
        _tostLabel = [[UILabel alloc]init];
//        _tostLabel.text = @"验证码已经发送到+ 86";
        _tostLabel.font = [UIFont systemFontOfSize:12.0];
    }
    return _tostLabel;
}

-(UILabel *)backLabel{
    if(!_backLabel){
        _backLabel = [[UILabel alloc]init];
        _backLabel.backgroundColor = [UIColor whiteColor];
        _backLabel.layer.borderWidth = 1;
        _backLabel.layer.borderColor = rgb(188, 188, 188).CGColor;
    }
    return _backLabel;
}

-(UITextField *)codeText{
    if(!_codeText){
        _codeText = [[UITextField alloc]init];
        _codeText.delegate = self;
        _codeText.placeholder = @"请输入验证码";
        [_codeText addTarget:self action:@selector(codeTextChange:) forControlEvents:UIControlEventEditingChanged];
    }
    return _codeText;
}

-(UIButton *)timeButton{
    if(!_timeButton){
        _timeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _timeButton.userInteractionEnabled = NO;
        [_timeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_timeButton addTarget:self action:@selector(onClickTimeButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _timeButton;
}

-(UILabel *)lineLabel{
    if(!_lineLabel){
        _lineLabel = [[UILabel alloc]init];
        _lineLabel.backgroundColor = rgb(188, 188, 188);
    }
    return _lineLabel;
}

-(UIButton *)registerButton{
    if(!_registerButton){
        _registerButton =[[UIButton alloc]init];
        [_registerButton setTitle:@"注册" forState:UIControlStateNormal];
        _registerButton.backgroundColor = rgb(229, 229, 229);
        _registerButton.userInteractionEnabled = NO;
        [_registerButton setTitleColor:rgb(132, 132, 132) forState:UIControlStateNormal];
//        [_registerButton addTarget:self action:@selector(pushNextViewController) forControlEvents:UIControlEventTouchUpInside];
    }
    return _registerButton;
}

-(void)setPhoneNumString:(NSString *)phoneNumString{
    _phoneNumString = phoneNumString;
    _tostLabel.attributedText = [self makeTostLabelAttributeText];
}

#pragma mark - textFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    //如果“键入值”在“0123456789”中，且输入框文字长度未达到6位时，可以键入
    if ([@"0123456789" containsString:string] && textField.text.length<=5) {
        return YES;
    }
    
    //如果输入的是“删除键”，也是可以键入的。
    if (string.length == 0) {
        return YES;
    }
    return NO;
}

#pragma mark - 定时器

-(void)GCDTime:(NSInteger)time{
//    __block NSInteger time = 5;
    __block typeof (time) blockTime = time;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0*NSEC_PER_SEC, 0*NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        if (blockTime < 1) {
            dispatch_source_cancel(timer); //结束
            NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:@"重新发送" attributes:@{NSForegroundColorAttributeName:rgb(56, 166, 243)}];
            //主线程更新UI
            dispatch_async(dispatch_get_main_queue(), ^{
                [_timeButton setAttributedTitle:string forState:UIControlStateNormal];
                _timeButton.userInteractionEnabled = YES;
            });
        }else{
            //主线程更新UI
            dispatch_async(dispatch_get_main_queue(), ^{
                [_timeButton setAttributedTitle:[self makeTimeButtonAttributeText:blockTime] forState:UIControlStateNormal];
            });
            blockTime --;
        }
    });
    dispatch_resume(timer);
}


@end
